<!DOCTYPE html>
<meta charset="utf-8">
<style>
.axis path,
.axis line {
	fill: none;
	stroke: black;
	shape-rendering: crispEdges;
}

.axis text {
	font-family: sans-serif;
	font-size: 11px;
}
.heatmap{
	/*top:110px;*/
	position: relative;
}

.g-hed {
    text-align: left;
    text-transform: uppercase;
    font-weight: bold;
    font-size:22px; 
    margin: 3px 0;
  }

  .g-source-bold {
    text-align: left;
    font-size:10px;
    font-weight: bold; 
  }

  .g-source {
    margin: 10px 0;
  }

  .g-source-bold {
    text-align: left;
    font-size:10px; 
  }

  .g-intro {
    font-size: 16px;
    margin: 0px 0px 10px 0px;
  }

  .g-labels {
    font-family: 'Proxima-Nova', sans-serif;
    fill: white;
    font-weight: bold;
    font-size: 14px;
  }

  .axis line {
    fill: none;
    stroke: #ccc;
    stroke-dasharray: 2px 3px;
    shape-rendering: crispEdges;
    stroke-width: 1px;
  }

  .axis text {
    font-family: 'Proxima-Nova', sans-serif;
    font-size: 13px;
    pointer-events: none;
    fill: #7e7e7e;
  }

  .y.axis text {
    text-anchor: end !important;
    font-size:14px;
    fill: #7e7e7e;
  }

  .domain {
    display: none;
  }

  .line {
    stroke: #2f5491;
    stroke-width: 3px;
    fill: none;
  }

  .overlay {
    fill: none;
    pointer-events: all;
  }

  .focus {
    font-size: 14px;
  }

  .focus circle {
    fill: #5e8dc9;
  }


</style>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<!-- <script src="http://d3js.org/d3.v3.min.js"></script> -->


<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js" charset="utf-8"></script>
<script src="http://labratrevenge.com/d3-tip/javascripts/d3.tip.v0.6.3.js"></script>
<div class="row">
	<div class="col heatmap">
	</div>
	<div class = "col">
		<h5 class="g-hed"></h5>
  <p class="g-intro"></p>
    <div class="g-chart"></div>
        <div class="g-source"><span class="g-source-bold"></span><span class="g-source-reg"></span></div>
    </div>
 	</div>
</div>


<script>

/*

negative color scales in increasing magnitude
#EF9FAE, #C76475, #781426

positive color scales in increasing magnitude
#ABDB92, #77B75B, #2E6E12

*/

/* supporting functions */

// Standard deviation
function RMS(arr){
	return Math.pow(arr.reduce(function(acc,pres){
		return acc+ Math.pow(pres,2);
	})/arr.length,.5)
}

// mean
function mean(arr){
	return arr.reduce(function(acc,prev){
		return acc+prev;
	})/arr.length;
}

var lPatchWidth=200;
var itemSize = 40,
cellSize = itemSize - 3,
margin = {top: 50, right: 20, bottom: 120, left: 110};

var data;

var width = 750 - margin.right - margin.left,
height = 500 - margin.top - margin.bottom;
var colorScale;

colorHold=["#D3D0CB","#F2D7EE","#D3BCC0","#A5668B","#69306D","#0E103D"]
colorLText=["0","1","2","3","4","5"]

function bandClassifier(val,multiplier)
{
	if(val>=0)
	{ 
// alert((Math.floor((val*multiplier)/(.33*multiplier))+1)>3?3:Math.floor((val*multiplier)/(.33*multiplier))+1);
return (Math.floor((val*multiplier)/(.33*multiplier))+1)>3?3:Math.floor((val*multiplier)/(.33*multiplier))+1
}
else{
//alert((Math.floor((val*multiplier)/(.33*multiplier)))<-3?-3:Math.floor((val*multiplier)/(.33*multiplier)));
return (Math.floor((val*multiplier)/(.33*multiplier)))<-3?-3:Math.floor((val*multiplier)/(.33*multiplier))
}
}


window.onload=function(){
	d3.csv('heatmap.csv', function ( response ) {


// data = response.filter(function( item ) {
//     if(item.ID == 1){
//     var newItem = {};
//     newItem.country = item.x;
//     newItem.product = item.y;
//     newItem.HotelID = item.ID;
//     newItem.value = +item.value;
//     return newItem;
//     }
// })

data = response.filter(function( item ) {
	if(item.ID == 112303){
		item.country = item.x;
		item.product = item.y;
		item.HotelID = item.ID;
		item.value = item.value;
		return item;
	}
})
invertcolors=0;
// Inverting color scale
if(invertcolors){
	colorHold.reverse();


}

var x_elements = d3.set(data.map(function( item ) { return item.product; } )).values(),
y_elements = d3.set(data.map(function( item ) { return item.country; } )).values();

var xScale = d3.scaleBand()
.domain(x_elements)
.range([0, x_elements.length * itemSize])
.paddingInner(20).paddingOuter(cellSize/2)

var xAxis = d3.axisBottom()
.scale(xScale)
.tickFormat(function (d) {
	return d;
});

var yScale = d3.scaleBand()
.domain(y_elements)
.range([0, y_elements.length * itemSize])
.paddingInner(.2).paddingOuter(.2);

var yAxis = d3.axisLeft()
.scale(yScale)
.tickFormat(function (d) {
	return d;
});


// Finding the mean of the data
var mean=window.mean(data.map(function(d){return +d.value}));

//setting percentage change for value w.r.t average
data.forEach(function(d){
	console.log(mean);
	d.perChange=(d.value-mean)/mean
})

colorScale = d3.scaleOrdinal()
.domain([-3,-2,-1,1,2,3])
.range(colorHold);

var rootsvg = d3.select('.heatmap')
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
var svg=rootsvg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

// tooltip
tooltip=d3.select("body").append("div").style("width","80px").style("height","40px").style("background","#C3B3E5")
.style("opacity","1").style("position","absolute").style("visibility","hidden").style("box-shadow","0px 0px 6px #7861A5").style("padding","10px");
toolval=tooltip.append("div");


var cells = svg.selectAll('rect')
.data(data)
.enter().append('g').append('rect')
.attr('class', 'cell')
.attr('width', cellSize)
.attr('height', cellSize)
.attr('y', function(d) { return yScale(d.country); })
.attr('x', function(d) { return xScale(d.product)-cellSize/2; })
.attr('fill', function(d) { return colorScale(window.bandClassifier(d.perChange,100));})
.attr("rx",3)
.attr("ry",3)
.on("mouseover",function(d){
	console.log(d);
//d3.select(this).attr("fill","#655091");
d3.select(this).style("stroke","orange").style("stroke-width","3px")
d3.select(".trianglepointer").transition().delay(100).attr("transform","translate("+(-((lPatchWidth/colorScale.range().length)/2+(colorScale.domain().indexOf(bandClassifier(d.perChange,100))*(lPatchWidth/colorScale.range().length) )))+",0)");

d3.select(".LegText").select("text").text(colorLText[colorScale.domain().indexOf(bandClassifier(d.perChange,100))])


})
.on("mouseout",function(){
//d3.select(this).attr('fill', function(d) { return colorScale(window.bandClassifier(d.perChange,100));});
d3.select(this).style("stroke","none");
tooltip.style("visibility","hidden");
})
.on("mousemove",function(d){
	tooltip.style("visibility","visible")
	.style("top",(d3.event.pageY-30)+"px").style("left",(d3.event.pageX+20)+"px");

	console.log(d3.mouse(this)[0])
	tooltip.select("div").html("<strong>"+d.product+"</strong><br/> "+(+d.value).toFixed(2))

})


svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.selectAll('text')
.attr('font-weight', 'normal');

svg.append("g")
.attr("class", "x axis")
.attr("transform","translate(0,"+(y_elements.length * itemSize +cellSize/2)+")")
.call(xAxis)
.selectAll('text')
.attr('font-weight', 'normal')
.style("text-anchor", "end")
.attr("dx", "-.8em")
.attr("dy", "-.5em")
.attr("transform", function (d) {
	return "rotate(-65)";
});

// Legends section


legends=svg.append("g").attr("class","legends")
.attr("transform","translate("+((width+margin.right)/2-lPatchWidth/2 -margin.left/2)+","+(350)+")");

// Legend traingle pointer generator
var symbolGenerator = d3.symbol()
.type(d3.symbolTriangle)
.size(64);

legends.append("g").attr("transform","rotate(180)").append("g").attr("class","trianglepointer")
.attr("transform","translate("+(-lPatchWidth/colorScale.range().length)/2+")")
.append("path").attr("d",symbolGenerator());
//Legend Rectangels
legends.append("g").attr("class","LegRect")
.attr("transform","translate(0,"+15+")")
.selectAll("rect").data(colorScale.range()).enter()
.append("rect").attr("width",lPatchWidth/colorScale.range().length+"px").attr("height","10px").attr("fill",function(d){ return d})
.attr("x",function(d,i){ return i*(lPatchWidth/colorScale.range().length) })

// legend text
legends.append("g").attr("class","LegText")
.attr("transform","translate(0,45)")
.append("text")
.attr("x",lPatchWidth/2)
.attr('font-weight', 'normal')
.style("text-anchor", "middle")
.text(colorLText[0])

// Heading 
rootsvg.append("g")
.attr("transform","translate(0,30)")
.append("text")
.attr("x",(width+margin.right+margin.left)/2)
.attr('font-weight', 'bold')
.attr('font-size', '22px')
.attr('font-family', 'Segoe UI bold')
.style("text-anchor", "middle")
.text("Hotel Characteristics Heatmap")


});
}
</script>
   <script>
//Margin conventions
var data1;
var margin = {top: 20, right: 70, bottom: 40, left: 35};

var widther = window.outerWidth;

var width = widther - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;

//Parses date for correct time format
var parseDate = d3.time.format("%Y-%m").parse;

//Divides date for tooltip placement
var bisectDate = d3.bisector(function(d) { return d.date; }).left;    

//Appends the svg to the chart-container div
var svg = d3.select(".g-chart").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

//Creates the xScale 
var xScale = d3.time.scale()
  .range([0, width]);

//Creates the yScale
var yScale = d3.scale.linear()
  .range([height, 0]);

//Defines the y axis styles
var yAxis = d3.svg.axis()
    .scale(yScale)
  .tickSize(-width)
  .tickPadding(8)
    .orient("left");

//Defines the y axis styles
var xAxis = d3.svg.axis()
    .scale(xScale)
  .tickPadding(8)
    .orient("bottom")
    .tickSize(height)
  .ticks(numTicks(width))
  .tickFormat(d3.time.format("%Y")); 

//line function convention (feeds an array)
var line = d3.svg.line()
  .x(function(d) { return xScale(d.date); })
  .y(function(d) { return yScale(d.num); });    

//Loads the data
d3.csv("TimeSeries.csv", ready);
function ready(err, data) {

    if (err) throw "error loading data";
  console.log("hello");

    // //FORMAT data
    // data.forEach(function(d) {
    //     d.num = +d.num;
    //  d.date = parseDate(d.date);
    // d.year = (d.date).getFullYear();
    // });

    data = data.filter(function( item ) {
        if(item.ID == 99766){
        item.num = +item.num;
        item.date = parseDate(item.date);
        return item;
        }
    });

    console.log(data);






  //Appends chart headline
    d3.select(".g-hed").text("Overall Rating of Hotel");

  //Appends chart intro text
 // d3.select(".g-intro").text("Chart intro text goes here. Write a short sentence describing the chart here.");

  data.sort(function(a,b) { return a.date - b.date; });

  //Defines the xScale max
  xScale.domain(d3.extent(data, function(d) { return d.date; }));

  //Defines the yScale max

  yScale.domain([0, 5]);


    //Appends the y axis
    var yAxisGroup = svg.append("g")
        .attr("class", "y axis")
        .call(yAxis);

    //Appends the x axis        
    var xAxisGroup = svg.append("g")
        .attr("class", "x axis")
        .call(xAxis);

  //Binds the data to the line
  var drawline = svg.append("path")
    .datum(data)
    .attr("class", "line")
    .attr("d", line);       

  //Tooltips
  var focus = svg.append("g")
      .attr("class", "focus")
      .style("display", "none");

  //Adds circle to focus point on line
  focus.append("circle")
      .attr("r", 4);

  //Adds text to focus point on line    
  focus.append("text")
      .attr("x", 9)
      .attr("dy", ".35em");    
  
  //Creates larger area for tooltip   
  var overlay = svg.append("rect")
      .attr("class", "overlay")
      .attr("width", width)
      .attr("height", height)
      .on("mouseover", function() { focus.style("display", null); })
      .on("mouseout", function() { focus.style("display", "none"); })
      .on("mousemove", mousemove);
  
  //Tooltip mouseovers            
  function mousemove() {
    var x0 = xScale.invert(d3.mouse(this)[0]),
        i = bisectDate(data, x0, 1),
        d0 = data[i - 1],
        d1 = data[i],
        d = x0 - d0.date > d1.date - x0 ? d1 : d0;
    focus.attr("transform", "translate(" + xScale(d.date) + "," + yScale(d.num) + ")");
    focus.select("text").text(d.num);
  }; 

  //Appends chart source
  //   d3.select(".g-source-bold")
  //   .text("SOURCE: ")
  //   .attr("class", "g-source-bold");

  // d3.select(".g-source-reg")
  //   .text("Chart source info goes here")
  //   .attr("class", "g-source-reg");  

        
  //RESPONSIVENESS
  d3.select(window).on("resize", resized);

  function resized() {

    //new margin
    var newMargin = {top: 10, right: 80, bottom: 20, left: 50};

    //Get the width of the window
    var w = d3.select(".g-chart").node().clientWidth;
    console.log("resized", w);

    //Change the width of the svg
    d3.select("svg")
      .attr("width", w);

    //Change the xScale
    xScale
      .range([0, w - newMargin.right]);

    //Update the line
    line = d3.svg.line()
      .x(function(d) { return xScale(d.date); })
      .y(function(d) { return yScale(d.num); }); 

    d3.selectAll('.line')
      .attr("d", line);  


    //Updates xAxis
    xAxisGroup
      .call(xAxis);   

    //Updates ticks
    xAxis
      .scale(xScale)
      .ticks(numTicks(w));

    //Updates yAxis  
    yAxis
      .tickSize(-w - newMargin.right)
  };

}

//Determines number of ticks base on width
function numTicks(widther) {
  if (widther <= 900) {
    return 4
    console.log("return 4")
  }
  else {
    return 12
    console.log("return 5")
  }
}

</script>
